<?php
/**
 * Notes:
 * Created by PhpStorm.
 * Author: TS
 * Date: 2019/10/13
 * Time: 22:55
 */

namespace app\index\controller;
use app\index\controller\Communication;

class WebSocket
{
    const HOST = '0.0.0.0';
    const PORT = '9527';
    const CHART_PORT = '9528';
    public $server = null;
    public $nowUser = [
        "10001" => "6",
        "10003" => "5"
    ];
    /**
     * 初始化WebSocket
     * WebSocket constructor.
     */
    public function __construct()
    {
        $this->server = new \Swoole\WebSocket\Server(self::HOST, self::PORT);

        $this->server->listen(self::HOST, self::CHART_PORT, SWOOLE_SOCK_TCP);
        //绑定事件
        $this->server->on('open',[$this,'onOpen']);
        $this->server->on('message',[$this,'onMessage']);
        $this->server->on('close',[$this,'onClose']);
        $this->server->on('request',[$this,'onRequest']);
        $this->server->on('start',[$this,'onStart']);
//        $this->server->on('push',[$this,'onPush']);
        //启动服务
        $this->server->start();

    }
    public function onStart(){
//        define('APP_PATH', __DIR__ . '/../application/');
//        require __DIR__ . '/../thinkphp/base.php';
        echo "The WebSocket start";
    }

    /**
     *客户端连接回调
     * @param $server
     * @param $request
     */
    public function onOpen($server,$request){
        $this->nowUser[$request->get['user_id']] = $request->fd;
        echo "handshake success with client-{$request->fd}\nuser_id-{$request->get['user_id']}";
    }

    /**
     * 客户端关闭回调
     * @param $server
     * @param $request
     */
    public function onClose($server,$request){
        unset($this->nowUser[$request]);
        echo "client-{ $request } closed\n";
    }

    /**
     * 接受到客户端请求回调
     * @param $server
     * @param $request
     */
    public function onMessage($server,$request){
        echo "接受到客户端：{$request->fd} 的数据：{$request->data}\n";
        $client_id = $request->fd;
        $data = $request->data;
//        $this->onPush($client_id,$request->data);
        $this->analyseRequest($client_id,$data);
    }

    /**
     * 解析客户端请求
     * @param $client_id
     * @param $requestData
     */
    public function analyseRequest($client_id,$requestData){
        $data = json_decode($requestData,true);
        $mod = $data['method'];
        if($mod == 1){
            $target = $data['target'];
            $res_data = [
                'method' => 'response',
                'code' => '0',
                'msg' => '',
                'data' => $data['data']
            ];
            if (isset($this->nowUser[$target])) {
                $temp = $data['target'];
                $data['target'] = $data['user_id'];
                $data['user_id'] = $temp;

                $data = json_encode($data);
                $this->onPush($this->nowUser[$target], $data);
                $res_data['code'] = 1;
                $res_data['msg'] = '发送成功';
             }else{
                $res_data['msg'] = '好友不在线';
            }
            $res_data = json_encode($res_data);
            $this->onPush($client_id,$res_data);
            return true;
        }
//        if($mod == 2){
//            $res_data = $this->analyseRequest($data['action'],$data['data']);
//            $this->onPush($client_id,$res_data);
//            return true;
//        }
    }

    /**
     * 解析Action
     * @param $action
     * @param $data
     * @return mixed
     */
    public function analyseAction($action,$data){
        $result = call_user_func_array(['Communication',$action],$data);
        return $result;
    }

    /**
     * 服务器向客户端推送
     * @param $client_id
     * @param $data
     */
    public function onPush($client_id,$data){
        $this->server->push($client_id,$data);
    }
    public function onRequest($request,$response){
        foreach ($this->server->connections as $fd) {
            // 需要先判断是否是正确的websocket连接，否则有可能会push失败
            if ($this->server->isEstablished($fd)) {
                $this->server->push($fd, $request->get['message']);
            }
        }
    }


    function sendPost($url, $post_data) {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $url = '../../public/index.php' . $url;
        $result = file_get_contents($url, false, $context);
        return $result;
    }
}

new WebSocket();
